$(function () {
    "use strict";

    // Set a value on each social apply button so that we can distinguish which is which.
    $.each($('ul.btnSocialApply'), function (idx, obj) {
        $(this).data('sabID', idx);

        // If the presentation method for this button is "pop", adjust the icon accordingly.
        if (j2w.SAB.presentation[idx] === 'pop') {
            $(this).find('img.sabPopUpIcon').addClass('rotated180');
        }
    });

    // Reveal the social apply buttons.
    $('ul.btnSocialApply').show();

    // Move the buttons off screen so that if the border shows, it's off screen
    $('.btnSocialApply ul.sub').css({
        top: '-10000',
        left: '-10000'
    });

    // *********************************************************************
    // ** Event Bindings
    // *********************************************************************

    // NOTE: Keep in mind when binding events that there are typically more than one apply now buttons on the page; be sure to e.stopImmediatePropagation when appropriate to prevent firing multiple events.

    $('.btnSocialApply > li a.main').keyup(function (e) {
        if (e.keyCode === 13) {
            $(this).mouseup();
        }
    });

    $('.btnSocialApply > li').bind('mouseup', function (e) {
        // Only handle clicks directly on the "apply now" buttons.
        if (e.target.className === 'main apply' || e.target.parentElement.className === 'main apply') {
            // Store which button was clicked.
            j2w.SAB.$activeButton = $(e.target).closest('.btnSocialApply');

            var $aAllSAButtons = $('.btnSocialApply ul.sub');

            // Hide all other social apply buttons but this one.
            $aAllSAButtons.not($(this).find('ul.sub')).hide();

            // Reset any existing UI state (errors, etc.)
            clearGetterErrorState();
            j2w.SAB.$activeButton.find('ul.sub li').show().end().find('li.loading').hide();
            j2w.SAB.$activeButton.find('.emailGetter').hide();

            // Toggle the visible state of this social apply button.
            $(this).find('ul.sub').toggle();

            // Resize all of the "start apply with" buttons to the width of the widest button.
            setMaxWidth($('.btnSocialApply .networkContainer:visible'));

            // Position the social apply button.
            sabPrepareTo(j2w.SAB.presentation[j2w.SAB.$activeButton.data('sabID')]);

            // Hide the social subscribe menu, if it is available.
            typeof closeSocialSubscribeOptions === 'function' ? closeSocialSubscribeOptions() : null;

            // Force the last social apply button on the page to show its contents completely, if it was the social apply button that was just clicked.
            scrollForSABDropDown();
        }

        e.stopImmediatePropagation();
    });

    // Consumes clicks that would otherwise activate the dropdown button, closing it.
    $('.btnSocialApply').click(function (e) {
        e.stopPropagation();
    });


    $('.btnSocialApply > li a.main').click(function (e) {
        e.preventDefault();
        e.stopImmediatePropagation();
    });

    $('.btnSocialApply .networkContainer').click(function (e) {
        var socialNetwork = $(this).find('a.startApply,a.manualApply').data('sn');

        switch (socialNetwork) {
            case 'li':
                // We need to indicate that the user started this apply so that the authentication can respond appropriately.
                j2w.SAB.li.applyStarted = true;

                positionGetterAndText(this, socialNetwork);

                break;

            case 'fb':
                positionGetterAndText(this, socialNetwork);

                break;

            case 'manual':
                $('.manualApply').trigger('click');

                break;

            case undefined:
                break;
        }

        scrollForSABDropDown();

        e.stopImmediatePropagation();
        e.preventDefault();
    });

    $('.manualApply').click(function (e) {
        if (j2w.SSO && j2w.SSO.isEnabled() && j2w.SSO.ready) {
            j2w.SSO.urlVars = {};
        }

        j2w.Apply.handleApplyNowButton(e);

        e.stopPropagation();
        e.preventDefault();
    });

    $('.btnSocialApply input.start').click(function (e) {
        submitEmailBinder(e, this);
    });

    $('.btnSocialApply input[name=email]').keyup(function (e) {
        if (e.which == 13) {
            $(this).next('input.start').trigger('click');
        } else if ($(this).val().length === 0) {
            clearGetterErrorState();
        }
    });

    $('.btnSocialApply a.helpA, .btnSocialApply .socialbutton-help-icon').bind('mouseup keyup', function (e) {
        if (e.keyCode === 13 || e.keyCode === undefined) {
            var $helpText = $(this).find('img').data('ht');

            if (e.keyCode === 13) {
                $(this).blur();
            }

            if ($helpText.length) {
                alert($helpText);
            }
        }
    });

    // Closes the pop-up menu when the user left-clicks outside of it. (This allows the user to right-click to paste their e-mail address, etc.)
    $(document).click(function (e) {
        if (e.which === 1) {
            closeSocialApplyOptions();
        }
    });
});

function clearGetterErrorState() {
    $('ul.btnSocialApply').find('.getterMsg').html('').hide().siblings('input[name=email]').removeClass('errorField');
}

function closeSocialApplyOptions() {
    $('.btnSocialApply ul.sub').hide();
    hideGetter();
    clearGetterErrorState();
}

// sabApplyHandler()
// Updates the UI and goes to apply.
function sabApplyHandler(options) {
    var $container = $('.btnSocialApply ul.sub'),
        beforeHeight = $container.height(),
        beforeWidth = $container.width();

    // Provide default values, but override them with those values passed in.
    options = $.extend({
        socialSrc : ''
    }, options);

    // Show the please wait indicator and hide the other options before proceeding.
    $container.find('li').toggle();
    $container.find('li.loading').css({
        width   : beforeWidth + 'px',
        padding : (beforeHeight - $('.loading div').height()) / 2 + 'px 0'
    });

    document.location.href = '/talentcommunity/apply/' + j2w.SAB.Args.get('jobID') + '/?reviewtoken=socialApply&tcsetuptype=social&socialsrc=' + options.socialSrc + '&email=' + j2w.SAB.email + '&locale=' + j2w.SAB.Args.get('locale');
}

// setSABErrorState()
//
function setSABErrorState(message) {
    j2w.SAB.$activeButton.find('.getterMsg').html(message.unescapeHTML()).show().siblings('input[name=email]').addClass('errorField');
}

// submitEmailBinder()
//
function submitEmailBinder(e, obj) {
    var $getter = j2w.SAB.$activeButton.find('.emailGetter');
    var $email = $getter.find('input[type=text]');

    if (j2w.Validation.isEmail($email.val())) {
        // Hide any previous error state.
        clearGetterErrorState();

        switch ($email.data('sn')) {
            case 'li':
                j2w.SAB.email = $email.val();
                socialApplyCheckLI();

                break;

            case 'fb':
                j2w.SAB.email = $email.val();
                socialApplyCheckFB();

                break;

            default:

                break;
        }
    } else if ($email.val().length) {
        setSABErrorState(jsStr.tcemailnotvalid);
        $email.focus().select();
        scrollForSABDropDown();
    } else {
        setSABErrorState(jsStr.tcemailaddressrequired);
        $email.focus();
        scrollForSABDropDown();
    }
}

// positionGetterAndText()
// Positions and shows the e-mail field and more text container, or submits the e-mail address if the user has already provided it.
function positionGetterAndText(obj, socialNetwork) {
    var $getter = $(obj).closest('ul').find('.emailGetter'),
        $email = $getter.find('input[type=text]'),
        $socialMoreText = $getter.find('.socialMoreText');

    // Keep track of the selected social network option, and populate the UI with the moretext value for it.
    oSASelected = j2w.SAB.Args.get('profileData')[$(obj).data('idx')];

    $socialMoreText.html(oSASelected.moretext).show();

    if (!oSASelected.moretext.length) {
        $socialMoreText.hide();
    }

    // First move the e-mail field where it belongs and set the social network type on it.
    $getter.appendTo($(obj).closest('li'));
    $email.data('sn',socialNetwork);

    // If there's already a valid e-mail address in the field, we skip showing it and submit the form.
    if (j2w.Validation.isEmail($email.val())) {
        $getter.find('.start').trigger('click');
    } else {
        $getter.show();
        $email.focus().select();
    }
}